<?php

namespace app\admin\service;

use app\admin\dao\ExternalSourceDao;
use app\common\job\ExternalSourcePush;
use app\common\model\ExternalSource;
use ShidianUtil\Utils\StringUtil;
use think\exception\ValidateException;
use think\facade\Queue;

/**
 * Class SourceService
 * @package app\admin\service
 */
class SourceService
{
    // dao
    private ExternalSourceDao $externalSourceDao;

    public function __construct(ExternalSourceDao $externalSourceDao)
    {
        $this->externalSourceDao = $externalSourceDao;
    }

    /**
     * 新增
     * @param array $params
     * @return  void
     */
    public function add(array $params): void
    {
        $sourceId = $params['source_id'] ?? null;
        $provinceAreasNum = $params['province_areas_num'] ?? null;
        $cityAreasNum = $params['city_areas_num'] ?? null;
        $sourceType = $params['source_type'] ?? '';
        $type_name = $params['type_name'] ?? '';

        if (is_blank($sourceId)) {
            throw new ValidateException('缺少[source_id]参数');
        }
        if (is_blank($provinceAreasNum)) {
            throw new ValidateException('缺少[province_areas_num]参数');
        }
        if (is_blank($cityAreasNum)) {
            throw new ValidateException('缺少[city_areas_num]参数');
        }

        $record = ExternalSource::where('sourceId', $sourceId)->find();
        if ($record) {

            if (StringUtil::equals($type_name, '精选')) {
                // 如果本次推送是精品案源就允许再次推送
                $record->wxStatus = ExternalSource::UNPUSH;
                $record->save();
            } else {
                // 普通案源不允许重复推送
                // throw new ValidateException('重复的案源');
                // 2023-8-20 案如云说，这里报错会导致他们卡住，这里不报错了，直接返回成功
                return;
            }
        } else {
            $data = [
                'sourceId' => $sourceId,
                'provinceAreasNum' => $provinceAreasNum,
                'cityAreasNum' => $cityAreasNum,
                'sourceType' => $sourceType,
                'source' => $params,
                'wxStatus' => ExternalSource::UNPUSH,
            ];
            $record = $this->externalSourceDao->insertActive($data, []);
        }

        // 添加推送
        $job_data = ['id' => $record->id];
        Queue::push(ExternalSourcePush::class, $job_data);

    }

}
